<template>
  <div class="q-pa-md q-gutter-sm">
    <q-tree
      no-nodes-label="添加目录"
      :nodes="apis"
      dense
      node-key="id"
      :filter="filter"
      v-model:selected="selected"
    >
      <template v-slot:default-header="prop">
        <div class="row items-center">
          <!-- <q-icon name="http" color="orange" size="28px" class="q-mr-sm" /> -->
          <div>
            <span @click="onNodeClick(prop.node)">{{ prop.node.name }}</span>
            <q-btn
              style="margin-left: 6px"
              size="xs"
              flat
              @click="onDelete(prop.node)"
              label="删除"
            />
          </div>
        </div>
      </template>
    </q-tree>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useQuasar } from "quasar";
import { invoke } from "@tauri-apps/api/tauri";
import { emitter, Endpoint } from "../boot/global_variable";
const $q = useQuasar();

const selected = ref(null);
const workplaceID = ref("");

class Node {
  constructor() {
    this.id = "";
    this.name = "";
    this.icon = "";
    this.children = [];
  }
}

/* 过滤-START ***********/
const filter = ref("");

// 节点
const apis = ref([]);

//点击
const onNodeClick = (node) => {
  emitter.emit("node_changed", node.id);
  console.log("[node_changed:emit]=>", node);
};

// 删除
const onDelete = async (node) => {
  const request = {
    url: Endpoint + "/api/v1/api/del",
    method: "POST",
    header: {
      "Content-Type": "application/json;charset=utf-8",
    },
    body: JSON.stringify({ id: node.id }),
  };
  console.log(request);
  await invoke("http_cmd", { request: request })
    .then((data) => {
      console.log("[RESULT]=>", data);
      reload();
    })
    .catch((error) => {
      console.log("[ERROR]=>", error);
    });

  emitter.emit("node_deleted", node.id);
  console.log("[node_deleted:emit]=>", node.id);
};

const reload = async () => {
  const request = {
    url: Endpoint + "/api/v1/api/list",
    method: "POST",
    header: {
      "Content-Type": "application/json;charset=utf-8",
    },
    body: JSON.stringify({ workplace_id: workplaceID.value }),
  };
  console.log(request);
  await invoke("http_cmd", { request: request })
    .then((data) => {
      console.log("[RESULT]=>", data);
      apis.value = JSON.parse(data.body);
    })
    .catch((error) => {
      console.log("[ERROR]=>", error);
    });
};

onMounted(() => {
  emitter.on("workplace_changed", async (wid) => {
    workplaceID.value = wid;
    reload();
  });
});

onUnmounted(() => {
  emitter.off("workplace_changed");
});
</script>
